<template>
	<view class="page-container">
		<u-navbar bgColor="#ffffff" :placeholder="true" :autoBack="true" borderBottom="1px solid #f5f7fa">
			<view slot="left" class="navbar-left">
				<u-icon name="arrow-left" color="#333333" size="22"></u-icon>
			</view>
			<view slot="title" class="navbar-title">个人资料</view>
		</u-navbar>

		<view class="content-container">
			<view class="employee-card">
				<!-- 完全保留你指定的头像区域代码 -->
				<view class="employee-header">
					<view class="avatar-container" @click="chooseAvatar" v-if="isEdit">
						<image :src="userInfo.avatar || '../../static/images/user.png'" class="avatar-img"></image>
						<view class="avatar-edit">
							<u-icon name="camera" size="20" color="#fff"></u-icon>
						</view>
					</view>
					<view class="avatar-container" v-else>
						<image :src="userInfo.avatar || '../../static/images/user.png'" class="avatar-img"></image>
					</view>
					<text class="employee-name">{{ userInfo.nickname || '未设置昵称' }}</text>
				</view>

				<view class="info-section">
					<view class="info-item-single">
						<text class="info-label">昵称:</text>
						<view class="info-value" v-if="!isEdit">{{ userInfo.nickname || '未填写' }}</view>
						<u-input v-else v-model="userInfo.nickname" placeholder="请输入昵称" class="info-input"></u-input>
					</view>

					<view class="info-item-single">
						<text class="info-label">手机号:</text>
						<view class="info-value" v-if="!isEdit">{{ userInfo.phone || '未填写' }}</view>
						<u-input v-else v-model="userInfo.phone" placeholder="请输入手机号" type="number"
							class="info-input"></u-input>
					</view>

					<view class="info-item-single">
						<text class="info-label">邮箱:</text>
						<view class="info-value" v-if="!isEdit">{{ userInfo.email || '未填写' }}</view>
						<u-input v-else v-model="userInfo.email" placeholder="请输入邮箱" type="email"
							class="info-input"></u-input>
					</view>

					<view class="info-item-single">
						<text class="info-label">性别:</text>
						<view class="info-value" v-if="!isEdit">{{ getGenderText(userInfo.gender) }}</view>
						<view class="gender-select" v-if="isEdit" @click="genderShow = true">
							<text>{{ getGenderText(userInfo.gender) }}</text>
							<u-icon name="arrow-down" size="16" color="#ccc"></u-icon>
						</view>
					</view>

					<view class="info-item-single">
						<text class="info-label">生日:</text>
						<view class="info-value" v-if="!isEdit">{{ userInfo.birth || '未填写' }}</view>
						<view class="birth-select" v-if="isEdit" @click="birthShow = true">
							<text>{{ userInfo.birth || '请选择生日' }}</text>
							<u-icon name="arrow-down" size="16" color="#ccc"></u-icon>
						</view>
					</view>

					<view class="info-item-single">
						<text class="info-label">简介:</text>
						<view v-if="!isEdit" class="info-value">
							<u--textarea v-model="userInfo.profile" placeholder="无" disabled count
								border="none"></u--textarea>
						</view>
						<u--textarea v-else v-model="userInfo.profile" placeholder="请输入个人简介" border="bottom" count
							maxlength="200"></u--textarea>
					</view>
				</view>
			</view>
		</view>

		<!-- 仅修改底部操作栏：添加取消按钮 -->
		<view class="bottom-operate-bar">
			<!-- 编辑状态：显示保存 + 取消 -->
			<view class="btn-group" v-if="isEdit">
				<view class="operate-btn cancel-btn" @click="cancelEdit">取消</view>
				<view class="operate-btn save-btn" @click="saveInfo">保存</view>
			</view>
			<!-- 非编辑状态：显示编辑 -->
			<view class="operate-btn" v-else @click="toggleEdit">编辑</view>
		</view>

		<u-picker :columns="[genderList]" :show="genderShow" keyName="label" @confirm="confirmGender"
			@cancel="genderShow = false"></u-picker>

		<u-datetime-picker mode="date" :show="birthShow" @confirm="confirmBirth" @cancel="birthShow = false"
			v-model="myDate"></u-datetime-picker>
	</view>
</template>

<script>
	import {
		getUserInfoApi,
		updateUserInfoApi,
		OssUpload
	} from "@/api/auth.js";

	export default {
		data() {
			return {
				isEdit: false,
				genderShow: false,
				birthShow: false,
				myDate: Number(new Date()),
				genderList: [{
						label: '男',
						value: 0
					},
					{
						label: '女',
						value: 1
					},
					{
						label: '保密',
						value: 2
					}
				],
				userInfo: {
					id: '',
					nickname: '',
					phone: '',
					avatar: '',
					birth: '',
					profile: '',
					gender: 2,
					email: ''
				}
			};
		},
		onLoad() {
			this.loadUserInfo();
		},
		methods: {
			// 进入编辑状态
			toggleEdit() {
				this.isEdit = true;
			},
			// 新增：取消编辑
			cancelEdit() {
				this.isEdit = false;
				// 可选：取消编辑时恢复原始数据（如需恢复可取消注释）
				// this.loadUserInfo();
			},
			async loadUserInfo() {
				try {
					const res = await getUserInfoApi();
					if (res.code === 200) {
						this.userInfo = {
							...res.data
						};
					}
				} catch (error) {
					console.error('加载用户信息失败:', error);
					uni.showToast({
						title: '加载失败',
						icon: 'error'
					});
				}
			},
			getGenderText(gender) {
				const genderMap = {
					0: '男',
					1: '女',
					2: '保密'
				};
				return genderMap[gender] || '未填写';
			},
			chooseAvatar() {
				uni.chooseImage({
					count: 1,
					sizeType: ['compressed'],
					sourceType: ['album', 'camera'],
					success: async (res) => {
						const tempFilePath = res.tempFilePaths[0];
						try {
							const uploadRes = await OssUpload(tempFilePath);
							console.log('原生上传返回结果:', uploadRes);
							if (uploadRes.code === 200 || uploadRes.code === 0) {
								this.userInfo.avatar = uploadRes.data || uploadRes.url || uploadRes;
								uni.showToast({
									title: '头像上传成功',
									icon: 'success'
								});
							} else {
								throw new Error(uploadRes.msg || '上传失败');
							}
						} catch (error) {
							console.error('头像上传失败:', error);
							uni.showToast({
								title: '头像上传失败',
								icon: 'error'
							});
						}
					},
					fail: (err) => {
						console.log('取消选择头像:', err);
					}
				});
			},
			confirmGender(e) {
				this.userInfo.gender = e.value[0].value;
				this.genderShow = false;
			},
			confirmBirth(e) {
				this.userInfo.birth = new Date(e.value).toISOString().slice(0, 10);
				this.birthShow = false;
			},
			saveInfo() {
				if (!this.userInfo.nickname) return uni.showToast({
					title: '昵称不能为空',
					icon: 'none'
				});
				if (this.userInfo.phone && !/^1[3-9]\d{9}$/.test(this.userInfo.phone)) {
					return uni.showToast({
						title: '手机号格式错误',
						icon: 'none'
					});
				}
				if (this.userInfo.email && !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(this.userInfo.email)) {
					return uni.showToast({
						title: '邮箱格式错误',
						icon: 'none'
					});
				}

				uni.$u.http.post('/Vip/updateInfo', this.userInfo)
					.then(res => {
						if (res.code === 200) {
							uni.showToast({
								title: '保存成功',
								icon: 'success'
							});
							this.isEdit = false;
							uni.setStorageSync('userInfo', this.userInfo);
						} else {
							uni.showToast({
								title: '保存失败',
								icon: 'none'
							});
						}
					})
					.catch(err => {
						console.error('保存信息失败', err);
						uni.showToast({
							title: '网络错误',
							icon: 'none'
						});
					});
			}
		}
	};
</script>

<style lang="scss" scoped>
	.navbar-left {
		display: flex;
		align-items: center;
	}

	.navbar-title {
		font-size: 32rpx;
		font-weight: 600;
		color: #333;
	}

	.page-container {
		min-height: 100vh;
		background-color: #f9fafb;
		padding-top: 88rpx;
		padding-bottom: 120rpx;
		box-sizing: border-box;
	}

	.content-container {
		margin: 0 auto;
		padding: 16px;
	}

	.employee-card {
		background: #fff;
		border-radius: 12rpx;
		box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
		padding: 16px;
	}

	.employee-header {
		display: flex;
		flex-direction: column;
		align-items: center;
		margin-bottom: 24px;
	}

	.avatar-container {
		width: 80px;
		height: 80px;
		border-radius: 50%;
		background: #e8f4fc;
		display: flex;
		align-items: center;
		justify-content: center;
		position: relative;
		margin-bottom: 12px;
		overflow: hidden;
	}

	.avatar-img {
		width: 100%;
		height: 100%;
	}

	.avatar-edit {
		position: absolute;
		bottom: 0;
		left: 0;
		right: 0;
		height: 30rpx;
		background: rgba(0, 0, 0, 0.5);
		display: flex;
		align-items: center;
		justify-content: center;
	}

	.employee-name {
		font-size: 18px;
		font-weight: 600;
		color: #333;
	}

	.info-section {
		background: #f9fafb;
		border-radius: 8px;
		padding: 16px;
		margin-bottom: 16px;
	}

	.info-item-single {
		display: flex;
		align-items: flex-start;
		margin-bottom: 12px;
		font-size: 14px;
		padding: 10rpx 0;
		border-bottom: 1px solid #f0f0f0;
		position: relative;

		&:last-child {
			border-bottom: none;
			margin-bottom: 0;
		}
	}

	.info-label {
		color: #6b7280;
		margin-right: 8px;
		width: 80px;
		flex-shrink: 0;
		font-size: 14px;
		line-height: 40rpx;
	}

	.info-value {
		color: #1f2937;
		flex: 1;
		line-height: 40rpx;
		word-wrap: break-word;
		word-break: break-all;
	}

	.info-input {
		flex: 1;
		height: 40rpx;
		font-size: 14px;
		border: none;
		padding: 0 16rpx;
		background: transparent;

		// 下划线样式
		&::after {
			content: '';
			position: absolute;
			bottom: 0;
			left: 88px;
			right: 0;
			height: 1px;
			background-color: #e5e7eb;
		}
	}

	.gender-select,
	.birth-select {
		flex: 1;
		display: flex;
		justify-content: space-between;
		align-items: center;
		line-height: 40rpx;
		font-size: 14px;
		color: #1f2937;

		// 下划线样式
		&::after {
			content: '';
			position: absolute;
			bottom: 0;
			left: 88px;
			right: 0;
			height: 1px;
			background-color: #e5e7eb;
		}
	}

	.bottom-operate-bar {
		position: fixed;
		bottom: 0;
		left: 0;
		right: 0;
		padding: 20rpx 30rpx;
		background: #fff;
		box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.05);
		z-index: 999;
		box-sizing: border-box;
	}

	// 新增：按钮组样式（保存+取消）
	.btn-group {
		display: flex;
		gap: 20rpx;
		width: 100%;
	}

	.operate-btn {
		width: 100%;
		height: 80rpx;
		line-height: 80rpx;
		text-align: center;
		font-size: 32rpx;
		border-radius: 40rpx;
		background: #e8f4fc;
		color: #1e88e5;
		border: 1px solid #1e88e5;
		transition: all 0.2s ease;
	}

	// 取消按钮样式
	.cancel-btn {
		background: #f5f5f5;
		color: #666;
		border: 1px solid #ddd;
	}

	// 保存按钮样式
	.save-btn {
		background: #1e88e5;
		color: #fff;
		border: none;
	}
</style>